package com.sgkusbcamdemo;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.gkusbsdk.SZUSBCommand;
import com.gkusbsdk.SZUSBFile;
import com.gkusbsdk.SZUSBFileInfo;
import com.gkusbsdk.SZUSBIFrame;
import com.qitianyong.selfclass.BUS_MESSAGE;
import com.qitianyong.selfclass.CONSTANT;
import com.qitianyong.selfclass.GKDevice;
import com.qitianyong.selfclass.GlideApp;
import com.qitianyong.selfclass.Message2EventBus;

import java.util.ArrayList;
import java.util.List;

public class GalleryActivity extends BaseActivity implements View.OnClickListener {

    private Button getCycleVideo;
    private Button getHurryVideo;
    private Button getPhoto;
    private Button getAll;
    private RecyclerView fileList;
    private FileListAdapter fileListAdapter;
    private int fileType;
    private ShowVideoDataDialog showVideoDataDialog;
    private int record_status_bak = SZUSBCommand.STATUS_RECORD.NORECORD_EXSIT_SD;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery);
        initView();
        record_status_bak = getIntent().getIntExtra("status", SZUSBCommand.STATUS_RECORD.NORECORD_EXSIT_SD);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                onBackPressed();
                return false;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onBackPressed() {
        GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_EXIT_FILELIST, null);
        super.onBackPressed();
    }

    private void initView() {
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        getCycleVideo = findViewById(R.id.get_cycle_video);
        getHurryVideo = findViewById(R.id.get_hurry_video);
        getPhoto = findViewById(R.id.get_photo);
        fileList = findViewById(R.id.file_list);
        getAll = findViewById(R.id.all);
        getCycleVideo.setOnClickListener(this);
        getHurryVideo.setOnClickListener(this);
        getPhoto.setOnClickListener(this);
        getAll.setOnClickListener(this);
        fileListAdapter = new FileListAdapter();
        fileList.setAdapter(fileListAdapter);

    }

    @Override
    public void onClick(View v) {
        showDialog();
        switch (v.getId()) {
            case R.id.get_cycle_video:
                fileType = SZUSBCommand.FILE_TYPE.CYCLE_FILE;
                break;
            case R.id.get_hurry_video:
                fileType = SZUSBCommand.FILE_TYPE.HURRY_FILE;
                break;
            case R.id.get_photo:
                fileType = SZUSBCommand.FILE_TYPE.PHOTO_FILE;
                break;
            case R.id.all:
                fileType = SZUSBCommand.FILE_TYPE.ALL_FILE;
                break;
        }
        fileList.setVisibility(View.VISIBLE);
        refresh();
    }
    private void refresh() {
        if(fileType == SZUSBCommand.FILE_TYPE.PHOTO_FILE){
            fileList.setLayoutManager( new GridLayoutManager(this, 5));
        }else {
            fileList.setLayoutManager( new LinearLayoutManager(this));
        }
        fileListAdapter.clearFiles();
        if( fileType == SZUSBCommand.FILE_TYPE.ALL_FILE){
            GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_GET_ALL_FILE, null);
        }else {
            GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_SEARCH_FILE, fileType);

        }
        showDialog();
    }

    public void onEventMainThread(Message2EventBus message) {

        switch (message.__what) {
            case BUS_MESSAGE.BUS_SEARCH_COMPLETE: {
                List<SZUSBFile> gkusbFileList = (List<SZUSBFile>) message.object;
                if (gkusbFileList == null) { // 请求失败
                    toast("获取失败");
                } else if (gkusbFileList.size() == 0) {
                    toast("暂无文件");
                }else {
                    toast("获取成功");

                }
                fileListAdapter.setFiles(gkusbFileList);
                cancelDialog();
                break;
            }
            case BUS_MESSAGE.BUS_SEARCH_ALL_FILE: {
                List<SZUSBFile> gkusbFileList = (List<SZUSBFile>) message.object;
                if (gkusbFileList == null) { // 请求失败
                    toast("获取失败");
                } else if (gkusbFileList.size() == 0) {
                    toast("暂无文件");
                }else {
                    toast("获取成功");

                }
                fileListAdapter.setFiles(gkusbFileList);
                cancelDialog();
                break;
            }
            case BUS_MESSAGE.BUS_FILEINFO_OK: {
                final SZUSBFileInfo fileInfo = (SZUSBFileInfo) message.object;
                cancelDialog();
                new AlertDialog.Builder(GalleryActivity.this)
                        .setMessage("获取成功  " + new String(fileInfo.__name) + " size=" + fileInfo.__size + " duration=" + fileInfo.__duration+"  thumb="+new String(fileInfo.__thumb_name)+"\n获取一帧h264预览图？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_GET_VIDEO_THUMB, fileInfo);

                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .show();

                break;
            }
            case BUS_MESSAGE.BUS_DELETE_PHOTO: {
                toast("删除图片成功");
                cancelDialog();
                refresh();
                break;
            }
            case BUS_MESSAGE.BUS_DELETE_VIDEO: {
                toast("删除视频成功");
                cancelDialog();
                refresh();
                break;
            }
            case BUS_MESSAGE.BUS_VIDEO_THUMB: {
                SZUSBIFrame object = (SZUSBIFrame) message.object;

                toast("获取视频缩略图成功 name="+new String(object.__name)+" size = "+object.__size+" byte[0]="+object.__iFrame[0]+" byte[1]="+object.__iFrame[1]+" byte[2]="+object.__iFrame[2]+" byte[3]="+object.__iFrame[3]+" byte[4]="+object.__iFrame[4]);
                cancelDialog();
                break;
            }
            case BUS_MESSAGE.BUS_VIDEO_THUMB_ERR: {
                toast("获取视频缩略图失败");
                cancelDialog();
                break;
            }
            case BUS_MESSAGE.BUS_LOCK_VIDEO: {
                toast("加锁成功");
                cancelDialog();
                refresh();
                break;
            }
            case BUS_MESSAGE.BUS_UNLOCK_VIDEO: {
                toast("解锁成功");
                cancelDialog();
                refresh();
                break;
            }
            case BUS_MESSAGE.BUS_DELETE_PHOTO_ERR:
            case BUS_MESSAGE.BUS_DELETE_VIDEO_ERR: {
                toast("删除失败");
                cancelDialog();
                refresh();
                break;
            }
            case BUS_MESSAGE.BUS_LOCK_VIDEO_ERR: {
                toast("加锁失败");
                cancelDialog();
                refresh();
                break;
            }
            case BUS_MESSAGE.BUS_UNLOCK_VIDEO_ERR: {
                toast("解锁失败");
                cancelDialog();
                refresh();
                break;
            }
            case BUS_MESSAGE.BUS_PLAYBACK_ERR: {
                toast("播放失败");
                cancelDialog();
                break;
            }
            case BUS_MESSAGE.BUS_PLAYBACK: {
                toast("播放成功");
                cancelDialog();
                if(showVideoDataDialog==null){
                    showVideoDataDialog = new ShowVideoDataDialog(this, (SZUSBFile) message.object);
                    showVideoDataDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            if(record_status_bak == SZUSBCommand.STATUS_RECORD.RECORDING) {
                                notifyEmptyBusMessage(BUS_MESSAGE.BUS_OPEN_RECORD);
                            }
                        }
                    });
                }else {
                    showVideoDataDialog.setGkusbFile((SZUSBFile) message.object);
                }
                    showVideoDataDialog.show();
                break;
            }
            case BUS_MESSAGE.BUS_STOP_PLAYBACK_ERR: {
                toast("停止播放失败");
                cancelDialog();
                break;
            }
            case BUS_MESSAGE.BUS_STOP_PLAYBACK: {
                toast("停止播放");
                cancelDialog();
                break;
            }
            case BUS_MESSAGE.BUS_PAUSE_PLAYBACK_ERR: {
                toast("暂停播放失败");
                cancelDialog();
                break;
            }
            case BUS_MESSAGE.BUS_PAUSE_PLAYBACK: {
                toast("暂停播放");
                cancelDialog();
                break;
            }
            case BUS_MESSAGE.BUS_RESUME_PLAYBACK_ERR: {
                toast("恢复播放失败");
                cancelDialog();
                break;
            }
            case BUS_MESSAGE.BUS_RESUME_PLAYBACK: {
                toast("恢复播放");
                cancelDialog();
                break;
            }
            case BUS_MESSAGE.BUS_OFFLINE: {
                finish();
                break;
            }
            case BUS_MESSAGE.BUS_PRINT: {
                cancelDialog();
                break;
            }
            default:
                break;
        }
    }



    class FileListAdapter extends RecyclerView.Adapter  {

        List<SZUSBFile> files = new ArrayList<>();

        public void setFiles(List<SZUSBFile> files) {
            this.files.clear();
            if(files!=null){
                this.files .addAll(files);
            }
            notifyDataSetChanged();
        }
        public void  clearFiles() {
            this.files.clear();
            notifyDataSetChanged();
        }
        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public int getItemViewType(int position) {
            return files.get(position).__lock;
        }


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if(viewType == SZUSBCommand.FILE_TYPE.PHOTO_FILE){
                return new IvHolder(View.inflate(parent.getContext(),R.layout.layout_iv,null));
            }else {
                return new TvHolder( View.inflate(parent.getContext(),android.R.layout.simple_list_item_1,null));
            }
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final SZUSBFile gkusbFile = files.get(position);
            if(getItemViewType(position) == SZUSBCommand.FILE_TYPE.PHOTO_FILE){
                IvHolder ivHolder = (IvHolder) holder;
                GlideApp
                        .with(CustomApp.customApp)
                        .load(gkusbFile)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .placeholder(R.mipmap.ic_launcher)
                        .centerInside()
                        .into(ivHolder.iv);
            }else {
                ((TvHolder) holder).tv.setText(new String(gkusbFile.__name));
            }
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final PopupMenu popupMenu = new PopupMenu(v.getContext(), v);
                    int popupMenuResId = 0;
                    final int itemViewType = getItemViewType(position);
                    switch (itemViewType) {
                        case SZUSBCommand.FILE_TYPE.CYCLE_FILE:
                            popupMenuResId = R.menu.cycle_file_menu;
                            break;
                        case SZUSBCommand.FILE_TYPE.HURRY_FILE:
                            popupMenuResId = R.menu.hurry_file_menu;
                            break;
                        case SZUSBCommand.FILE_TYPE.PHOTO_FILE:
                            popupMenuResId = R.menu.photo_file_menu;

                            break;
                    }
                    popupMenu.getMenuInflater().inflate(popupMenuResId, popupMenu.getMenu());
                    popupMenu.show();
                    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem item) {
                            int cmdType;

                            switch (item.getItemId()) {
                                //暂不支持获取视频缩略图
                                case R.id.delete:
                                    if (itemViewType == SZUSBCommand.FILE_TYPE.PHOTO_FILE) {
                                        cmdType = CONSTANT.COMMAND.CMD_DELETE_PHOTO;
                                    } else {
                                        cmdType = CONSTANT.COMMAND.CMD_DELETE_VIDEO;
                                    }
                                    break;
                                case R.id.lock:
                                    cmdType = CONSTANT.COMMAND.CMD_LOCK_VIDEO;
                                    break;
                                case R.id.unlock:
                                    cmdType = CONSTANT.COMMAND.CMD_UNLOCK_VIDEO;
                                    break;
                                case R.id.play:
                                    cmdType = CONSTANT.COMMAND.CMD_PLAYBACK;
                                    break;
                                case R.id.get_file_info:
                                    cmdType = CONSTANT.COMMAND.CMD_GET_FILEINFO;
                                    break;
                                default:
                                    return false;
                            }
                            GKDevice.getInstance().addToFirstNoRepeated(cmdType, gkusbFile);
                            showDialog();
                            return true;
                        }
                    });
                }
            });

        }



        @Override
        public int getItemCount() {
            return files.size();
        }
        class IvHolder extends RecyclerView.ViewHolder {

            private ImageView iv;

            public IvHolder(View itemView) {
                super(itemView);
                this.iv = itemView.findViewById(R.id.iv);
            }
        }
        class TvHolder extends RecyclerView.ViewHolder {

            private TextView tv;

            public TvHolder(View itemView) {
                super(itemView);
                this.tv = (TextView) itemView;
            }
        }


    }

}
